<?php

namespace App\Service\Common;

use App\Enums\OpenShop\Feishu\CacheEnum;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class WeatherService
{
    /**
     * 根据地区名字获得地区ID
     * @param $area
     * @return int|mixed|string
     */
    public static function getAreaIdByArea($area)
    {
        $res = Http::withHeaders([
            'Authorization' => 'APPCODE ' . 'bfda20b54da6479cb76a5de60ef0a02d',
            'Content-Type' => 'application/json; charset=utf-8',
        ])->get(config('weather.getAreaIdUrl'), [
            'area' => $area,
        ])->json();
        if (!isset($res['showapi_res_body'])) {
            return '';
        }
        return  $res['showapi_res_body']['list'][0]['areaid'] ?? 0;
    }


    public static function getWeatherByArea($area)
    {
        if (!mb_strlen($area)) {
            return [];
        }
        if(Cache::has(CacheEnum::TIGER_FEISHU_WEATHER . urlencode($area))){
            return Cache::get(CacheEnum::TIGER_FEISHU_WEATHER . urlencode($area));
        }
        //通过地区获得天气
        $res = Http::withHeaders([
            'Authorization' => 'APPCODE ' . config('weather.appCode'),
            'Content-Type' => 'application/json; charset=utf-8',
        ])->get(config('weather.getWeatherUrl'), [
            'area' => $area,
        ])->json();
        if (!isset($res['showapi_res_body'])) {
            return [];
        }
        $weather = [
            [
                'field' => 'weather',
                'text'  => $res['showapi_res_body']['now']['weather'] ?? '-',
            ],[
                'field' => 'temperature',
                'text'  => ($res['showapi_res_body']['now']['temperature'] ?? '-') . '℃',
            ]
        ];
        Cache::put(CacheEnum::TIGER_FEISHU_WEATHER . urlencode($area), $weather, strtotime(date('Y-m-d') . ' 23:59:59') - time());
        return $weather;
    }

}
